<?php
/**
 * Created by b17
 * 2/29/12 8:32 PM
 */

namespace Managers;

class Subscribers extends BaseManager
{
    const TABLE = '\Catalog\Subscribers';
    protected $__table = self::TABLE;

    private $_salt;

    private $_delimiter = '.';

    public function __construct()
    {
        parent::__construct();
        $this->salt = \Zend_Registry::get('config')->crypto->salt;
    }

    protected function _createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('s')
            ->from($this->__table, 's')
            ->andWhere('s.isDel = 0');
        return $qb;
    }

    public function getList()
    {
        $qb = $this->_createQueryBuilder();
        $res = $qb->getQuery()->getArrayResult();
        return $res;
    }

    public function create(array $values)
    {
        if ($this->isExists($values['email'])) {
            throw new \LogicException('Email already exists.');
        }

        $entity = new \Catalog\Subscribers();
        $entity->setCreatedAt(new \DateTime());
        $entity->setIsDel(false);
        $entity->setEmail($values['email']);

        $this->_em->persist($entity);
        $this->flush();
        return $entity;
    }

    public function isExists($email)
    {
        $qb = $this->_createQueryBuilder()
            ->andWhere('s.email = :email')->setParameter('email', $email);
        $res = $qb->getQuery()->getArrayResult();

        return (boolean)count($res);
    }

    public function getToken($params)
    {
        $data = array();
        $data[] = is_object($params) ? $params->getId() : $params['id'];
        $sign = is_object($params) ? $params->getEmail() : $params['email'];
        $data[] = $this->_sign($sign);
        return join($this->_delimiter, $data);
    }

    private function _sign($value)
    {
        return sha1($this->_salt . $value);
    }

    public function checkToken($token)
    {
        $params = explode($this->_delimiter, $token);
        if (count($params) != 2) {
            return false;
        }
        list ($id, $sign) = $params;
        $data = $this->getById($id);
        if (!$data) {
            return false;
        }
        if ($sign == $this->_sign($data['email'])) {
            return $data;
        }
        return false;
    }

    public function getById($id)
    {
        $qb = $this->_createQueryBuilder()
            ->andWhere('s.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    public function unSubscribe($token)
    {
        if ($data = $this->checkToken($token)) {
            $this->delete($data['id']);
            return $data;
        }
        return false;
    }
}
